import requests
import time
import hashlib
import os
from qiniu import Auth,put_data
access_key = 'ZbAuqFKprS0fXUL9WRYMv28tiIHJhkT1Q99JfdWe'

secret_key = 'vDxb0r56YjDx0gpnvjWmTtHwioWPxQwTvNm0DKU-'

# 空间名
bucket_name = 'zhou-kou'

bucket_url = 'http://zhoukou.image.dianxuebang.com/'
def getApi():
    url = 'http://zk.dianxuebang.com/index.php/admin/publicclass/apiurl'
    return [requests.get(url).text]
# 获取某个字符最后一次出现位置
def index_of_str(s1, s2):
    start = len(s1)
    print(start)
    stop = 0
    while start >= stop:
        if s1[start-1:start] is s2:
            return start
        start -= 1
    return -1
def create_auth():
    input_name = hashlib.md5()
    this_time_str = str(int(time.time())).encode(encoding='utf-8')
    input_name.update(this_time_str)
    file_path = 'd:/python/' + str(time.strftime("%Y-%m-%d", time.localtime()))
    if os.path.exists(file_path) == False:
        os.makedirs(file_path)
    return file_path
def download_videofile(video_links):
    root = create_auth()
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36",
        "upgrade-insecure-requests": "1",
    }

    for link in video_links:
        file_name = link.split('/')[-1]
        print("文件下载:%s" % file_name)
        r = requests.get(link, headers=headers)
        with open(root+'/'+file_name, 'wb') as f:
            f.write(r.content)

        print("%s 下载完成!\n" % file_name)
    print("所有视频下载完成!")
    return root+'/'+file_name, file_name


def upload_qiniu(path, file_name):
    with open(path,'rb') as f:
        data = f.read()
    q = Auth(access_key=access_key, secret_key=secret_key)
    token = q.upload_token(bucket=bucket_name)
    ret, res = put_data(token, file_name, data=data)
    if res.status_code != 200:
        raise Exception("upload failed")
    else:
        return bucket_url + file_name
path, file_name = download_videofile(getApi())
data = upload_qiniu(path, file_name)
print(data)